// store/loading.js 或者直接在 store/index.js 中定义

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    isLoading: false,
    pendingRequests: 0, // 用来追踪并发请求的数量
  },
  mutations: {
    incrementPendingRequests(state) {
      state.pendingRequests++;
      if (state.pendingRequests === 1) {
        state.isLoading = true;
      }
    },
    decrementPendingRequests(state) {
      if (state.pendingRequests > 0) {
        state.pendingRequests--;
        if (state.pendingRequests === 0) {
          state.isLoading = false;
        }
      }
    }
  },
  actions: {
    startLoading({ commit }) {
      commit('incrementPendingRequests');
    },
    endLoading({ commit }) {
      commit('decrementPendingRequests');
    },
    delayedEndLoading({ dispatch }, delay = 0) {
      setTimeout(() => {
        dispatch('endLoading');
      }, delay);
    }
  },
  getters: {
    isLoading: state => state.isLoading
  }
});

export default store;